//express 框架
const express =require("express");  //用来引入web框架
const app=express();
const Cookies =require('cookies');
const User = require("./models/user")
const Category = require("./models/category")
const config = require('./config')
//app.use(express.json());
app.use(express.urlencoded());

app.use(async function (req,res,next){
  req.cookies=new Cookies(req,res);
  if(req.cookies.get("__user")){
      let user =JSON.parse(req.cookies.get("__user"))
      req.user = await User.findById(user._id);
  }
  next();
});

//router setting
app.use('/admin', require('./routers/admin'))
app.use('/api', require('./routers/api'))
app.use('/', require('./routers/main'))


//模板引擎配置
const swig=require("swig");  //swig是JS模板引擎
app.set('views','./views');
app.set('view engine','html');//默认模板文件后缀
app.engine('html',swig.renderFile);
swig.setDefaults({cache:false});//todo :发布时删除

/*
app.get("/",function(req,res,next){
    res.render("index",{userName:"zhangsan"});
    //TODO:fetch some data
})
*/

app.use('/public',express.static(__dirname+"/public"));
app.listen(config.app.port,config.app.host);

// 引入数据库
var mongoose = require('mongoose');
//连接到mongoose 端口号为27017 数据库名为pblog
mongoose.connect('mongodb://localhost:27017/pBlog',{useNewUrlParser:true,useUnifiedTopology:true},
    function (err){
    if(err){
        console.log(`db connect failure`)
    }else {
        console.log(`db connect successfully on port${27017}`)
          }
    });
